import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class CustomCollectors {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1);
        System.out.println();
        List<List<Integer>> subbedList = list.stream().map(x -> x + x).collect(CustomCollectors.subList(5));
        System.out.println(subbedList);
        List<Integer> combinedList = subbedList.stream().map(x -> x.stream().map(xx -> xx - 1).collect(Collectors.toList())).collect(CustomCollectors.combineList());
        System.out.println(combinedList);

        Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(Function.identity(), Function.identity(), newOpt()));
        Map<Integer, Integer> map2 = list.stream().collect(CustomCollectors.toMapOld(Function.identity(), Function.identity()));
        Map<Integer, Integer> map3 = list.stream().collect(CustomCollectors.toMapNew(Function.identity(), Function.identity()));
        Map<Integer, Integer> map4 = list.stream().collect(CustomCollectors.toMapOld(Function.identity()));
        Map<Integer, Integer> map5 = list.stream().collect(CustomCollectors.toMapNew(Function.identity()));
        System.out.println(map);
        System.out.println(map2);
        System.out.println(map3);
        System.out.println(map4);
        System.out.println(map5);
    }


    private static final Set<Collector.Characteristics> CH_ID
            = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));

    /**
     * 根据数量进行分批，流式操作（当前只支持串行流）
     *
     * @param subSize 分批大小
     * @param <T>     类型
     * @return 分批结果
     */
    public static <T>
    Collector<T, ?, List<List<T>>> subList(int subSize) {
        if (subSize <= 0) {
            throw new RuntimeException("subSize can not be less than 1");
        }

        Supplier<List<List<T>>> supplier = ArrayList::new;
        @SuppressWarnings("Convert2Diamond")
        BiConsumer<List<List<T>>, T> accumulator = new BiConsumer<List<List<T>>, T>() {
            int nowCount = 0;
            int mod = 0;
            List<T> nowList;

            @Override
            public void accept(List<List<T>> a, T t) {
                if (nowCount >= subSize) {
                    nowCount = 0;
                    mod++;
                }
                if (a.size() <= mod) {
                    a.add(new ArrayList<>(subSize));
                }
                nowList = a.get(mod);
                nowList.add(t);

                nowCount++;
            }
        };

        return new CollectorImpl<>(supplier,
                accumulator
                ,
                (left, right) -> {
                    left.addAll(right);
                    return left;
                },
                CH_ID);
    }

    /**
     * 将多个T类型的list合并成一个list
     *
     * @param <T> 类型
     * @return 合并结果
     */
    public static <T> Collector<List<T>, ?, List<T>> combineList() {
        Supplier<List<T>> supplier = ArrayList::new;
        BiConsumer<List<T>, List<T>> accumulator = (a, t) -> {
            if (t == null || t.isEmpty()) {
                return;
            }
            a.addAll(t);
        };

        return new CollectorImpl<>(supplier,
                accumulator
                ,
                (left, right) -> {
                    left.addAll(right);
                    return left;
                },
                CH_ID);
    }

    public static <K, U> Collector<U, ?, Map<K, U>> toMapOld(Function<? super U, ? extends K> keyMapper) {
        return Collectors.toMap(keyMapper, v -> v, oldOpt(), HashMap::new);
    }

    /**
     * Collectors.toMap(keyMapper, valueMapper, oldOpt(), HashMap::new);
     */
    public static <T, K, U> Collector<T, ?, Map<K, U>> toMapOld(Function<? super T, ? extends K> keyMapper,
                                                                Function<? super T, ? extends U> valueMapper) {
        return Collectors.toMap(keyMapper, valueMapper, oldOpt(), HashMap::new);
    }

    /**
     * Collectors.toMap(keyMapper, valueMapper, newOpt(), HashMap::new);
     */
    public static <T, K, U> Collector<T, ?, Map<K, U>> toMapNew(Function<? super T, ? extends K> keyMapper,
                                                                Function<? super T, ? extends U> valueMapper) {
        return Collectors.toMap(keyMapper, valueMapper, newOpt(), HashMap::new);
    }

    /**
     * Collectors.toMap(keyMapper, valueMapper, newOpt(), HashMap::new);
     */
    public static <K, U> Collector<U, ?, Map<K, U>> toMapNew(Function<? super U, ? extends K> keyMapper) {
        return Collectors.toMap(keyMapper, v -> v, newOpt(), HashMap::new);
    }


    public static <U> BinaryOperator<U> oldOpt() {
        return (k1, k2) -> k1;
    }

    public static <U> BinaryOperator<U> newOpt() {
        return (k1, k2) -> k2;
    }

    @SuppressWarnings("unchecked")
    private static <I, R> Function<I, R> castingIdentity() {
        return i -> (R) i;
    }

    /**
     * Simple implementation class for {@code Collector}.
     *
     * @param <T> the type of elements to be collected
     * @param <R> the type of the result
     */
    static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
        private final Supplier<A> supplier;
        private final BiConsumer<A, T> accumulator;
        private final BinaryOperator<A> combiner;
        private final Function<A, R> finisher;
        private final Set<Characteristics> characteristics;

        CollectorImpl(Supplier<A> supplier,
                      BiConsumer<A, T> accumulator,
                      BinaryOperator<A> combiner,
                      Function<A, R> finisher,
                      Set<Characteristics> characteristics) {
            this.supplier = supplier;
            this.accumulator = accumulator;
            this.combiner = combiner;
            this.finisher = finisher;
            this.characteristics = characteristics;
        }

        CollectorImpl(Supplier<A> supplier,
                      BiConsumer<A, T> accumulator,
                      BinaryOperator<A> combiner,
                      Set<Characteristics> characteristics) {
            this(supplier, accumulator, combiner, castingIdentity(), characteristics);
        }

        @Override
        public BiConsumer<A, T> accumulator() {
            return accumulator;
        }

        @Override
        public Supplier<A> supplier() {
            return supplier;
        }

        @Override
        public BinaryOperator<A> combiner() {
            return combiner;
        }

        @Override
        public Function<A, R> finisher() {
            return finisher;
        }

        @Override
        public Set<Characteristics> characteristics() {
            return characteristics;
        }
    }


}
